package com.travel.utils.xeixinDecrypt;

import net.sf.json.JSONObject;
import org.apache.tomcat.util.codec.binary.Base64;

public class WXCore {

    private static final String WATERMARK = "watermark";
    private static final String APPID = "appid";
    /**
     * 解密数据
     * @return
     * @throws Exception
     */
    public static String decrypt(String appId, String encryptedData, String sessionKey, String iv){
        String result = "";
        try {
            AES aes = new AES();
            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if(null != resultByte && resultByte.length > 0){
                result = new String(WxPKCS7Encoder.decode(resultByte));
                JSONObject jsonObject = JSONObject.fromObject(result);
                String decryptAppid = jsonObject.getJSONObject(WATERMARK).getString(APPID);
                if(!appId.equals(decryptAppid)){
                    result = "";
                }
            }
        } catch (Exception e) {
            result = "";
            e.printStackTrace();
        }
        return result;
    }


    public static void main(String[] args) throws Exception{
        String appId = "wxeb10f6f98bcf8d2a";
        String encryptedData = "B8hjSl4mSE8PXqbNVqoko/2BmV9WMy/Jy1T2gWqw0zgn0jScTnvP9cqOvcFz6ccetOcNGXyzk2/gqg8wYpur9R3Pnayo0C9mEAvg0oa0htRtAkc9NuwVB5ZRvOypIVQ4+f7pSFE8El9Ga8RmhlHwid7A85e+zID9AkqN4qAJreSSo1wIISywCUorC7B9KNbOk5tDi0sPlwTMVEmfyrBr9SAqIML7VwFKMguPEbRLR1jr49us5wnahHC8ctFfNvaN8WV1MhY+iC/KfgDH69dd0MQ8iA+xbSEqC3d1HYLRJP9qo+oKoNsdGh9MhOHIw4vmZwQUarV7AnUOkjrejv4/dCcpEPxM2T0M6nbGSJb3osSh7a32CHyFYRMHhycypfAXYWl9XE8rTCQCWf5UsMfT4OOn7QCZ3ctiUO4M4SLFSJ78gtrGwd6mQYI7ACJnVig0a73qaMHXJfi5GbFU7l+c1w==";
        String sessionKey = "M7VEpy3GDI+pFc5719/rwg==";
        String iv = "u6K3447p7s0b/iy3o7JS6w==";
        System.out.println(decrypt(appId, encryptedData, sessionKey, iv));
    }
}
